﻿using System.Collections.Generic;
using System.Linq;

namespace SW.DDD.Domain
{
    /// <summary>
    /// 值对象,需实现原子值相等比较
    /// </summary>
    public abstract class ValueObject
    {
        protected abstract IEnumerable<object?> GetAtomicValues();

        public override bool Equals(object? obj)
        {
            if (null == obj)
                return false;

            if (GetType() != obj.GetType())
                return false;

            var other = (ValueObject)obj;
            var thisValues = GetAtomicValues();
            var otherValues = other.GetAtomicValues();
            return thisValues.SequenceEqual(otherValues);
        }

        public override int GetHashCode()
        {
            return GetAtomicValues()
                   .Select(x => x?.GetHashCode() ?? 0)
                   .Aggregate((x, y) => x ^ y ^ 31);
        }

        public static bool operator ==(ValueObject? left, ValueObject? right)
        {
            return left?.Equals(right) ?? Equals(right, null);
        }

        public static bool operator !=(ValueObject? left, ValueObject? right)
        {
            return !(left == right);
        }
    }
}
